import {ajax} from '../utlis/utils.js'

const tableBox = document.querySelector('table')
const tbodyBox = document.querySelector('.tb')
const addBtn = document.querySelector('.addBtn')
const bt = document.querySelector('.bt')
const fbr = document.querySelector('.fbr')
const date = document.querySelector('.date')
const qa = document.querySelector('.qa')
const qb = document.querySelector('.qb')
const qc = document.querySelector('.qc')
const gxBtn = document.querySelector('.gx')

let list = []

if (!localStorage.getItem('list')) {
  getList()
  async function getList() {
    const { info } = await ajax({
      url: 'https://api.iynn.cn/mock?t=2',
      dataType: 'json'
    })
    console.log(info)
    localStorage.setItem('list', JSON.stringify(info.data))
    list = info.data
    bindHtml(list)
  }
} else {
  list = JSON.parse(localStorage.getItem('list'))
  bindHtml(list)
}

function bindHtml (a) {
  tbodyBox.innerHTML = a.reduce((prev, item, index) => {
    return prev + `
      <tr>
        <td>${index + 1}</td>
        <td>${item.title}</td>
        <td>${item.user}</td>
        <td>${item.date}</td>
        <td>
          <button type="button" class="del" data-id="${index}">删除</button>
          <button type="button" class="edit" data-id="${index}">编辑</button>
        </td>
      </tr>
    `
  }, '')
}

// 新增
addBtn.addEventListener('click', addHandler)
function addHandler(e) {
  e.preventDefault()
  list.push({
    id: list.length,
    title: bt.value,
    user: fbr.value,
    date: date.value
  })
  localStorage.setItem('list',JSON.stringify(list))
  bindHtml(list)
  location.replace(document.referrer)
}

// 删除
tbodyBox.addEventListener('click', tbHandler)
function tbHandler(e) {
  e.preventDefault()
  if (e.target.className === 'del') { 
    const ix = e.target.dataset.id - 0
    list = list.filter((item, index) =>{ return index !== ix})
    localStorage.setItem('list',JSON.stringify(list))
    bindHtml(list)
  }
  if (e.target.className === 'edit') { 
    $('#myModal').modal('show')
    const iq = e.target.dataset.id - 0
    qa.value = list[iq].title
    qb.value = list[iq].user
    qc.value = list[iq].date
    localStorage.setItem('id', iq)
  }
}

// 编辑
gxBtn.onclick = function () {
  const d = localStorage.getItem('id')
  list[d].title = qa.value
  list[d].user = qb.value
  list[d].date = qc.value
  localStorage.setItem('list',JSON.stringify(list))
  bindHtml(list)
  location.replace(document.referrer)
}


